<template>
  <div class="problem-detail-layout">
    <a-spin :loading="loading" tip="加载中..." style="width: 100%; height: 100%">
      <a-split
        v-if="problem"
        class="problem-split"
        :style="{ height: splitHeight }"
        min="300px"
        max="0.75"
        v-model:size="splitSize"
      >
        <template #first>
          <div class="left-pane">
            <a-tabs default-active-key="problem" type="line" class="problem-tabs" @change="handleTabChange">
              <a-tab-pane key="problem" >
                <template #title><icon-file /> 题目描述</template>
                <div class="tab-content">
                  <div class="problem-header">
                    <h1>{{ problem.id }}. {{ problem.title }}</h1>
                    <div class="problem-meta">
                      <a-tag :color="difficultyColor">{{ difficultyText }}</a-tag>
                      <span class="stats">通过率: {{ acceptedRate }}</span>
                      <!-- 可以添加点赞/收藏等 -->
                    </div>
                    <div class="problem-tags">
                      <a-tag
                        v-for="tag in problem.tagsList"
                        :key="tag.id"
                        color="blue"
                        size="small"
                      >
                        {{ tag.name }}
                      </a-tag>
                    </div>
                  </div>

                  <a-divider margin="0" />

                  <div class="problem-description">
                    <MarkdownViewer :value="problem.content" />
                  </div>
                </div>
              </a-tab-pane>

              <a-tab-pane key="solutions" >
                <template #title><icon-book /> 题解</template>
                <div class="tab-content solutions-container">
                  <SolutionList 
                    ref="solutionListRef"
                    :problem-id="problemId"
                    @load-solutions="handleLoadSolutions"
                  />
                </div>
              </a-tab-pane>

              <a-tab-pane key="submissions">
                <template #title><icon-history /> 提交记录</template>
                <div class="tab-content submissions-container">
                  <!-- 用组件来显示，提交记录 -->
                  <a-table 
                    :columns="submitRecordColumns" 
                    :data="submitRecords" 
                    :pagination="false" 
                    @rowClick="handleRowClick" 
                  />
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>
        </template>

        <template #second>
          <div class="right-pane">
            <CodeEditor
              ref="codeEditorRef"
              v-model="editorCode"
              :language="selectedLanguage"
              :options="{ minimap: { enabled: false } }"
              @language-change="handleLanguageChange"
              style="flex: 1; height: 100%;"
            />
            <div class="editor-footer">
              <a-button @click="runCode" disabled>
                <template #icon><icon-play-arrow /></template>运行
              </a-button>
              <a-button
                type="primary"
                @click="submitCode"
                :loading="submitting"
                :disabled="submitting"
              >
                <template #icon><icon-check /></template>提交
              </a-button>
            </div>
            <!-- 运行/提交结果显示区域 -->
            <!-- 原结果区域已移除，将在抽屉中显示 -->
          </div>
        </template>
      </a-split>
    </a-spin>
    
    <!-- 运行/提交结果抽屉 -->
    <a-drawer 
      :visible="resultDrawerVisible"
      @cancel="resultDrawerVisible = false"
      @ok="resultDrawerVisible = false"
      title="运行/提交结果"
      width="800px"
      unmountOnClose
    >
      <a-spin :loading="judging" style="width: 100%;">
        <template #element>
          <p v-if="judgingMessage">{{ judgingMessage }}</p>
          <p v-else-if="judging">正在判题中...</p>
          <template v-else-if="latestSubmit">
            <!-- 判题结果状态 -->
            <div :class="['result-status-line', resultClass]">
              <div class="result-status">{{ resultStatusText }}</div>
            </div>
            <!-- 执行用时和内存消耗 -->
            <div class="result-info-line">
              <div class="result-info">
                <span>执行用时: {{ latestSubmit.judgeInfo?.time || 0 }} ms</span>
                <span>内存消耗: {{ latestSubmit.judgeInfo?.memory || 0 }} KB</span>
              </div>
            </div>

            <!-- 显示编译错误或运行错误信息 -->
            <div
              v-if="latestSubmit.status === 3 && latestSubmit.judgeInfo?.errorType"
              class="error-message"
            >
              <h4>{{ latestSubmit.judgeInfo.errorType }}</h4>
              <pre class="error-detail">{{ latestSubmit.judgeInfo.message }}</pre>
            </div>

            <!-- 失败用例信息 -->
            <div
              v-else-if="
                latestSubmit.status === 3 && latestSubmit.judgeInfo?.failedCases?.length
              "
              class="failed-cases"
            >
              <div class="failed-cases-header">
                <h4>失败用例信息:</h4>
              </div>
              <div
                v-for="(failedCase, index) in latestSubmit.judgeInfo.failedCases"
                :key="index"
                class="case-item"
              >
                <h4>
                  用例 #{{ failedCase.caseIndex + 1 }}
                  <a-tag :color="failedCaseColor(failedCase)">{{
                    failedCase.reason
                  }}</a-tag>
                </h4>
                <div class="case-content">
                  <div class="case-input">
                    <strong>输入:</strong>
                    <pre>{{ failedCase.input }}</pre>
                  </div>
                  <div class="case-output">
                    <strong>预期输出:</strong>
                    <pre>{{ failedCase.expectedOutput }}</pre>
                  </div>
                  <div class="case-output">
                    <strong>实际输出:</strong>
                    <pre>{{ failedCase.actualOutput }}</pre>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 显示提交的代码 -->
            <div v-if="latestSubmit?.code" class="submitted-code-area">
              <h4>提交的代码:</h4>
              <MonacoEditor
                :model-value="latestSubmit.code"
                :language="latestSubmit.language.toLowerCase()"
                :options="{ readOnly: true, minimap: { enabled: false } }"
                style="height: 400px;"
              />
            </div>

          </template>
          <p v-else>提交代码后，结果将显示在此处...</p>
        </template>
      </a-spin>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, onUnmounted, h } from 'vue'
import { useRoute } from 'vue-router'
import { useEditorStore } from '@/stores/editor.ts'
import { getProblemVoByIdApi } from '@/api/problem/problem'
import CodeEditor from '@/components/CodeEditor.vue'
import MarkdownViewer from '@/components/MarkdownViewer.vue'
import MonacoEditor from '@/components/MonacoEditor.vue'

import {
  IconFile,
  IconBook,
  IconHistory,
  IconPlayArrow,
  IconCheck,
} from '@arco-design/web-vue/es/icon'
import { Tag, Message, Drawer } from '@arco-design/web-vue'
import { problemSubmitApi, getSubmitDetailApi, getSubmitListPageVoApi } from '@/api/problem/submit'
import SolutionList from '@/components/SolutionList.vue'
import { getSolutionListPageVoApi } from '@/api/problem/solution'

// -------- 路由和状态 --------
const route = useRoute()
const problemId = computed(() => Number(route.params.id))
const problem = ref<API.ProblemVO | null>(null) // Use API.ProblemVO directly
const loading = ref(true)
const editorCode = ref('') // 编辑器中的代码
const editorStore = useEditorStore()
const selectedLanguage = ref(editorStore.selectedLanguage) // 使用存储的语言
const codeEditorRef = ref<InstanceType<typeof CodeEditor> | null>(null)
const submitting = ref(false) // 是否正在提交代码
const judging = ref(false) // 是否正在判题
const judgingMessage = ref() // 判题提示信息
let submitTimer: number | null = null // 防抖定时器

// 控制结果抽屉的显示
const resultDrawerVisible = ref(false);

// -------- 布局相关 --------
const splitSize = ref(0.5) // 分割面板比例
const splitHeight = ref('100%') // 使用100%而非固定高度

// -------- 提交记录相关 --------
const submitRecordColumns = [
  {
    title: '状态',
    dataIndex: 'status',
    ellipsis: true,
    tooltip: true,
    width: 100,
    render: ({record}: {record: API.Problem.SubmitVo}) => {
      if (record.status === 1) {
        return h(Tag, { color: 'blue' }, () => '判题中')
      } else if (record.status === 2) {
        return h(Tag, { color: 'green' }, () => '通过')
      } else if (record.status === 3) {
        return h(Tag, { color: 'red' }, () => '失败')
      } else {
        return h(Tag, { color: 'gray' }, () => '待判题')
      }
    }
  },
  {
    title: '语言',
    dataIndex: 'language',
    ellipsis: true,
    width: 100
  },
  {
    title: '执行时间 (ms)',
    dataIndex: 'judgeInfo.time',
    ellipsis: true,
    width: 150
  },
  {
    title: '内存 (KB)',
    dataIndex: 'judgeInfo.memory',
    ellipsis: true,
    tooltip: { position: 'left' },
    width: 100
  }
]

const submitRecords = ref<API.Problem.SubmitVo[]>([])

const solutionListRef = ref<InstanceType<typeof SolutionList> | null>(null)

// -------- 计算属性 --------
const difficultyColor = computed(() => {
  if (!problem.value) return 'blue'
  const map: Record<string, string> = {
    EASY: 'green',
    MEDIUM: 'orange',
    HARD: 'red'
  }
  return map[problem.value.difficulty] || 'blue'
})

const difficultyText = computed(() => {
  if (!problem.value) return ''
  const map: Record<string, string> = {
    EASY: '简单',
    MEDIUM: '中等',
    HARD: '困难'
  }
  return map[problem.value.difficulty] || problem.value.difficulty
})

const acceptedRate = computed(() => {
  if (!problem.value || !problem.value.submitNum) return '0.0%'
  const { submitNum, acceptedNum } = problem.value
  return submitNum > 0 ? `${((acceptedNum / submitNum) * 100).toFixed(1)}%` : '0.0%'
})

// -------- API 调用 --------
const fetchProblemDetail = async () => {
  loading.value = true
  try {
    const res = await getProblemVoByIdApi(problemId.value)
    if (res.code === 0 && res.data) {
      problem.value = res.data
      editorCode.value = ``
    } else {
      console.error('获取题目详情失败:', res.message)
      // 可以添加错误提示
    }
  } catch (error: any) {
    console.error('获取题目详情异常:', error)
    Message.error(error.message || '获取题目详情异常')
  } finally {
    loading.value = false
  }
}

const fetchSubmitRecords = async () => {
  const res = await getSubmitListPageVoApi({
    problemId: problemId.value,
  })
  if (res.code === 0 && res.data) {
    submitRecords.value = res.data.records
  }
}

// -------- 事件处理 --------
const handleLanguageChange = (language: string) => {
  selectedLanguage.value = language
}

const handleTabChange = (key: string) => {
  if (key === 'submissions') {
    fetchSubmitRecords()
  } else if (key === 'solutions') {
    // 延迟一下，确保组件已经加载
    nextTick(() => {
      solutionListRef.value?.fetchSolutions()
    })
  }
}

// 添加防抖功能
const debounce = (fn: Function, delay: number) => {
  return (...args: any[]) => {
    if (submitTimer) clearTimeout(submitTimer)
    submitTimer = window.setTimeout(() => {
      fn(...args)
    }, delay)
  }
}

// 添加结果相关状态
const latestSubmit = ref<API.Problem.SubmitVo | null>(null) // 明确类型
// 轮询计时器
let pollTimer: number | null = null

// 判断结果状态的样式
const resultClass = computed(() => {
  if (!latestSubmit.value) return ''

  switch (latestSubmit.value.status) {
    case 2:
      return 'success'
    case 3:
      return 'error'
    default:
      return ''
  }
})

// 获取状态文本
const resultStatusText = computed(() => {
  if (!latestSubmit.value) return ''

  const statusMap: Record<number, string> = {
    0: '等待判题',
    1: '判题中',
    2: '通过',
    3: '失败'
  }

  return statusMap[latestSubmit.value.status] || '未知状态'
})

// 获取失败用例的颜色
const failedCaseColor = (failedCase: any) => {
  const reason = failedCase.reason
  if (reason.includes('内存')) return 'orange'
  if (reason.includes('超时')) return 'yellow'
  return 'red'
}

// 提交代码实现
const submitCode = debounce(async () => {
  if (submitting.value) return // 防止重复提交

  submitting.value = true
  judging.value = true
  judgingMessage.value = '正在提交代码...'

  // 清除之前的轮询
  if (pollTimer) {
    clearInterval(pollTimer)
    pollTimer = null
  }

  // 清除之前的latestSubmit
  latestSubmit.value = null;

  try {
    // 提交代码
    const res = await problemSubmitApi({
      language: selectedLanguage.value,
      code: editorCode.value,
      problemId: problemId.value
    } as API.Problem.ProblemSubmitRequest)

    judgingMessage.value = '代码已提交，正在判题中...'

    // 提交记录的id
    const submitId = res.data

    // 轮询判题结果
    pollTimer = window.setInterval(async () => {
      try {
        const submitRes = await getSubmitDetailApi(Number(submitId))
        if (submitRes.code === 0 && submitRes.data) {
          latestSubmit.value = submitRes.data

          // 判断是否结束
          if (submitRes.data.status === 2 || submitRes.data.status === 3) {
            // 判题完成
            clearInterval(pollTimer as number)
            pollTimer = null
            judging.value = false
            judgingMessage.value = ''

            // 显示结果提示并打开抽屉
            const isSuccess = submitRes.data.status === 2
            Message[isSuccess ? 'success' : 'error'](isSuccess ? '提交成功' : '提交失败')
            resultDrawerVisible.value = true; // 打开抽屉
          }
        }
      } catch (error) {
        console.error('轮询判题结果失败:', error)
      }
    }, 1000) // 每秒轮询一次
  } catch (error: any) {
    judging.value = false
    Message.error(error.message || '提交失败')
  } finally {
    submitting.value = false
  }
}, 500) // 500ms防抖

// 处理提交记录行点击
const handleRowClick = async (record: API.Problem.SubmitVo) => {
  if (!record.id) return; // 确保有提交ID

  // 显示加载状态并打开抽屉
  judging.value = true;
  judgingMessage.value = '正在加载判题详情...';
  latestSubmit.value = null; // 清除之前的旧结果
  resultDrawerVisible.value = true; // 打开抽屉

  try {
    const res = await getSubmitDetailApi(record.id);
    if (res.code === 0 && res.data) {
      latestSubmit.value = res.data;
    } else {
      Message.error(res.message || '获取判题详情失败');
      resultDrawerVisible.value = false; // 关闭抽屉
    }
  } catch (error: any) {
    console.error('获取判题详情异常:', error);
    Message.error(error.message || '获取判题详情异常');
    resultDrawerVisible.value = false; // 关闭抽屉
  } finally {
    judging.value = false;
    judgingMessage.value = ''; // 清除加载提示
  }
}

const runCode = () => {
  // 功能暂未实现，按钮已禁用
  console.log('运行代码功能待实现')
}

// 处理加载题解列表
const handleLoadSolutions = async (params: API.Problem.SolutionQueryRequest) => {
  try {
    const res = await getSolutionListPageVoApi(params)
    if (res && res.data && res.code === 0) {
      solutionListRef.value?.updateSolutionData({
        records: res.data.records,
        total: Number(res.data.total)
      })
    }
  } catch (error) {
    console.error('获取题解列表失败', error)
    Message.error('获取题解列表失败')
  }
}

// -------- 生命周期钩子 --------
onMounted(() => {
  fetchProblemDetail()
})

onUnmounted(() => {
  // 清理定时器
  if (submitTimer) clearTimeout(submitTimer)
  if (pollTimer) clearInterval(pollTimer as number)
})
</script>

<style scoped>
.problem-detail-layout {
  height: 768px; /* 修改为100%而不是固定高度 */
  overflow: hidden;
  background-color: var(--color-bg-1);
}

.problem-split {
  height: 100%; /* 修改为100%而不是固定高度 */
  border: none; /* 移除默认边框 */
  min-height: 760px;
}

:deep(.arco-split-trigger-vertical) {
  height: auto;
}

.left-pane,
.right-pane {
  height: 100%;
  overflow: hidden; /* 父级隐藏溢出 */
  display: flex;
  flex-direction: column;
  background-color: var(--color-bg-1);
}

.left-pane {
  padding: 0;
}

.right-pane {
  padding: 12px 16px;
}

.problem-tabs {
  height: 100%;
  display: flex;
  flex-direction: column;
  border-right: 1px solid var(--color-border-2); /* 分割线 */
}

.problem-tabs :deep(.arco-tabs-nav) {
  padding: 0 16px;
}

.problem-tabs :deep(.arco-tabs-content) {
  flex-grow: 1; /* 占据剩余空间 */
  overflow: auto; /* 父级隐藏 */
  padding: 0; /* 移除内边距 */
}

.tab-content {
  padding: 16px 20px;
  height: 100%;
  overflow-y: hidden; /* 内部滚动 */
}

.problem-header {
  margin-bottom: 16px;
}

.problem-header h1 {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 8px;
  color: var(--color-text-1);
}

.problem-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.stats {
  font-size: 13px;
  color: var(--color-text-3);
}

.problem-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.problem-description {
  padding: 12px 0;
  line-height: 1.7;
  color: var(--color-text-1);
  font-size: 14px;
}

/* 确保v-html渲染的内容样式正确 */
.problem-description :deep(p) {
  margin-bottom: 1em;
}

.problem-description :deep(pre) {
  background-color: var(--color-fill-2);
  padding: 12px;
  border-radius: 4px;
  overflow-x: auto;
  margin: 1em 0;
  font-family: 'Fira Code', monospace;
  font-size: 13px;
}

.problem-description :deep(code) {
  font-family: 'Fira Code', monospace;
  background-color: var(--color-fill-3);
  padding: 0.2em 0.4em;
  border-radius: 3px;
  font-size: 0.9em;
}

.problem-description :deep(strong) {
  font-weight: 600;
}

.case-container {
  margin-top: 20px;
}

.case-container h3 {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  color: var(--color-text-1);
}

.case-item {
  margin-bottom: 16px;
  background-color: var(--color-fill-1);
  border: 1px solid var(--color-border);
  border-radius: 4px;
  padding: 16px;
}

.case-item h4 {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 8px;
  color: var(--color-text-1);
}

.case-content {
  font-family: 'Fira Code', monospace;
  font-size: 13px;
}

.case-input strong,
.case-output strong {
  display: block;
  margin-bottom: 4px;
  color: var(--color-text-2);
  font-weight: 500;
}

.case-content pre {
  background-color: var(--color-fill-2);
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
  margin: 0;
  line-height: 1.5;
}

.editor-footer {
  padding: 10px 0;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 12px;
  border-top: 1px solid var(--color-border);
  margin-top: 8px;
}

/* 调整抽屉内容样式 */
/* .drawer-result-content {
  padding: 16px;
} */

/* 隐藏原来的结果区域 */
.result-area {
  display: none;
}

.result-status-line {
  padding: 8px 0;
  /* border-bottom: 1px solid var(--color-border-2); */
  margin-bottom: 10px;
}

.result-info-line {
  padding: 8px 0;
  /* border-bottom: 1px solid var(--color-border-2); */
  margin-bottom: 10px;
}

.result-status {
  font-size: 18px;
  font-weight: bold;
}

.result-info span {
  margin-right: 20px; /* Adjusted from margin-left to margin-right for spacing between time and memory */
  color: var(--color-text-2);
}

.error-message,
.failed-cases {
  margin-top: 10px;
}

.error-detail,
.case-input pre,
.case-output pre {
  background-color: var(--color-fill-1);
  padding: 10px;
  border-radius: 4px;
  white-space: pre-wrap; /* 保持换行和空格 */
  word-break: break-all; /* 长单词换行 */
  overflow: auto; /* 允许滚动 */
}

.failed-cases-header {
  margin-bottom: 10px;
}

.case-item {
  border: 1px solid var(--color-border-2);
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
}

.case-item h4 {
  margin-top: 0;
  margin-bottom: 5px;
}

.case-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 10px;
}

.case-input,
.case-output {
  /* background-color: var(--color-fill-2); */
  background-color: var(--color-fill-2); /* Add background color */
  padding: 10px;
  border-radius: 4px;
  /* overflow: auto; */
}

.case-input strong,
.case-output strong {
  display: block;
  margin-bottom: 5px;
}

/* 成功和失败状态的颜色 */
.result-status-line.success .result-status {
  color: var(--color-success-6);
}

.result-status-line.error .result-status {
  color: var(--color-danger-6);
}

.solutions-container,
.submissions-container {
  min-height: 300px;
  display: flex;
  padding: 0 !important;
  color: var(--color-text-3);
  width: 100%;
  overflow: auto; /* 添加滚动 */
  scrollbar-width: none;
}

.solutions-container {
  flex-direction: column;
}

:deep(.arco-tabs-nav-type-line .arco-tabs-tab) {
  margin: 0 16px;
  padding: 10px 0;
}

:deep(.arco-tabs-nav-type-line .arco-tabs-tab-title) {
  font-size: 14px;
}

:deep(.arco-tabs-content) {
  padding-top: 0 !important;
}

:deep(.arco-tabs-pane) {
  height: 100%;
  overflow: hidden; /* 防止pane溢出 */
}

/* Webkit 浏览器滚动条样式 */
.tab-content::-webkit-scrollbar {
  width: 6px;
}

.tab-content::-webkit-scrollbar-track {
  background: transparent;
}

.tab-content::-webkit-scrollbar-thumb {
  background-color: var(--color-fill-4);
  border-radius: 3px;
}

.tab-content::-webkit-scrollbar-thumb:hover {
  background-color: var(--color-text-4);
}

.error-message {
  width: 100%;
  margin-bottom: 16px;
}

.error-message h4 {
  font-size: 14px;
  color: var(--color-danger);;
  margin-bottom: 8px;
}

.error-detail {
  background-color: var(--color-fill-2);
  padding: 12px;
  border-radius: 4px;
  border-left: 3px solid var(--color-danger);;
  overflow-x: auto;
  white-space: pre-wrap;
  font-size: 12px;
  line-height: 1.5;
  color: var(--color-text-1);
  font-family: 'Fira Code', monospace;
}

:deep(.arco-tabs-content, .solutions-container) {
  scrollbar-width: none;
}

.submitted-code-area {
  margin-top: 20px;
}

.submitted-code-area h4 {
  font-size: 14px;
  margin-bottom: 10px;
  color: var(--color-text-1);
}

/* Adjust Monaco Editor container height */
.submitted-code-area .monaco-editor-container {
  height: 400px; /* Or any desired fixed height */
}

</style>
